require "import"
import "str"

pid=...

rc4=import "mods.minicrypto"

--import "android.support.v4.app.*"
--import "android.support.v4.view.*"
import "android.support.v4.widget.*"

topbar_click=0

this.setContentView(loadlayout ({
  RelativeLayout,
  layout_width="fill",
  layout_height="fill",
  --visibility=4,
  backgroundColor=背景色,
  --orientation="vertical",
  --elevation="2%w",
  paddingTop=状态栏高度,
  {
    RelativeLayout,
    layout_width="fill",
    layout_height="56dp" ,
    gravity="center",
    padding="16dp",
    --backgroundColor=0xffffffff,
    elevation="2dp",
    paddingTop="8dp",
    paddingBottom="8dp",
    onClick=function()
      if topbar_click+2 > tonumber(os.time()) then
        ObjectAnimator.ofInt(loadb, "scrollY", {loadb.scrollY,0})
        .setDuration(256)
        .setInterpolator(luajava.newInstance("android.view.animation.DecelerateInterpolator"))
        .start()
       else
        topbar_click=tonumber(os.time())
      end
    end;
    {
      ImageView,
      src="drawable/back.png",
      layout_height="fill",
      layout_width="44dp",
      foreground=波纹(波纹色),
      onClick=function ()
        this.finish()
      end,
      padding="9dp",
      colorFilter=图标色,
    },
    {
      ImageView,
      src="drawable/dots.png",
      layout_height="fill",
      layout_width="44dp",
      foreground=波纹(波纹色),
      padding="9dp",
      colorFilter=图标色,
      layout_alignParentRight=true,
      onClick=function ()
        对话框操作()
      end,
    },
    {
      TextView,
      layout_width="fill",
      layout_height="fill",
      gravity="center",
      --layout_gravity="center",
      text="脑筋急转弯",
      textSize="20sp",
      textColor=文字色,
    },
  },
  {
    SwipeRefreshLayout;
    id="swipe1";
    layout_height="-1";
    layout_width="-1";
    {
      ScrollView,
      layout_height="-1";
      layout_width="-1";
      id="loadb";
      {
        LinearLayout,
        layout_width="fill",
        orientation="vertical",
        id = "daan",
        {
          LinearLayout,
          paddingTop="56dp" ,
        };
        {
          LinearLayout;
          orientation="vertical";
          layout_height="-1";
          layout_width="-1";
          {
            ImageView;
            --layout_height=activity.Width/800*450;
            layout_width="-1";
            --scaleType="centerCrop";
            src="drawable/naotu.jpg";
            id="pho_top";
            adjustViewBounds=true,
          };
          {
            LinearLayout;
            orientation="vertical";
            layout_height="-1";
            layout_width="-1";
            padding="16dp";
            {
              TextView;
              layout_width="-1";
              layout_height="-2";
              gravity="center";
              textSize="14sp";
              textColor=次要文字色;
              background="#10000000";
              layout_marginBottom="16dp";
              text="长按标题收藏本篇，下滑刷新内容（点击此消息不再提示）";
              padding="8dp";
              id="czts";
            };
            {
              TextView;
              layout_width="-1";
              layout_height="-2";
              gravity="left|center";
              textSize="20sp";
              textColor=文字色;
              id="today_title";
              layout_marginBottom="12dp";
            };
            {
              TextView;
              layout_width="-1";
              layout_height="-2";
              gravity="left|center";
              textSize="14sp";
              textColor=次要文字色;
              id="today_author";
              layout_marginBottom="16dp";
            };
            {
              TextView;
              layout_width="-1";
              layout_height="-2";
              textSize="16sp";
              textColor=文字色;
              id="today_text";
              gravity="left|center";
              layout_marginBottom="16dp";
            };
          };
        };
      };
      --scroll
    },
  },
  {
    LinearLayout,
    layout_width="fill",
    layout_height="56dp" ,
    foreground=上下渐变({背景色,深透,淡透}),
  },
}))

function 对话框操作()
  local edt=AlertDialog.Builder(this)
  -- .setCancelable(false)
  .setTitle("选择操作")
  .setItems({"添加收藏","分享内容","复制内容"}, function (d,n)
    local hiscon=today_title.Text.."\n    "..today_text.Text
    if n==1 then
      if utf8.len(hiscon)<=100 then
        texta=utf8.sub(hiscon,1,utf8.len(hiscon)-1).."……"
       else
        texta=utf8.sub(hiscon,1,100).."……"
      end

      textn=texta.."\n（复制此消息，打开闲言APP阅读全文）\n&MS"..tostring(now_content).."&\nhttp://m.pp.cn/detail.html?appid=8050563&ch_src=pp_dev&ch=default\n——闲言APP "..slogan
      shareText(textn)
     elseif n==2 then
      copyText(hiscon.."\n    ——闲言APP "..slogan)
     elseif n==0 then
      io.open(句子收藏..os.time().."("..#hiscon..")","w+"):write([[{
soup=]].."[["..hiscon.."]]"..[[,
type=]].."[[急转弯]]"..[[,
}]]):close()
      toast ("已加收藏，可在灵感中管理")
    end
  end)
  local ed=edt.show()
  local pw=ed.getWindow()
  --.setWindowAnimations(R.style.BottomDialog_Animation)
  --.setBackgroundDrawable(ColorDrawable(0))
  .setGravity(Gravity.BOTTOM)
  圆角(pw,背景色,{0,0,0,0,0,0,0,0})
  local lp=pw.getAttributes()
  lp.width=w
  pw.setAttributes(lp)
  pw.setDimAmount(0.35)
end



local aid={swipe1}
for i=1,#aid do
  aid[i].setProgressViewOffset(true,dp2px(56),dp2px(32+56))
  aid[i].setColorSchemeColors({文字色})
  aid[i].setProgressBackgroundColorSchemeColor(背景色)
end
aid=nil

today_text.setLineSpacing(48,0.5)

function isVip()
  if activity.getSharedData("vip_time")~=nil and activity.getSharedData("vip_time")~="已到期" and activity.getSharedData("vip_time")~="未开通" then
    return true
   else
    toast("您还不是会员或未登录")
    swipe1.setRefreshing(false)
    pho_top.setImageBitmap(loadbitmap(activity.getLuaDir().."/drawable/naotu.jpg"))
    pho_top.onClick=function()
      if activity.getSharedData("password")~=nil then
        activity.newActivity("sup")
       else
        toast("请先登录")
        activity.newActivity("login",{"sup"})
      end
    end
  end
end

daan.onClick=function()
  toast("请等待初始化完成")
end


math.randomseed(os.time())
math.random()

local urls = "http://wap.cmiyu.com"

function reLoadText()
  if thepage then
    Http.get(urls.."/njmy/"..thepage[math.random(#thepage)],
    nil,"gb2312",
    function(code, body)
      swipe1.setRefreshing(false)
      if code == 200 then
        local bodys = string.match(body,"<ul>(.-)</ul>")
        local eTab = {}
        for v in bodys:gmatch("<li>(.-)</li>") do
          local toAb = #eTab+1
          eTab[toAb] = {}
          eTab[toAb]["url"] = v:match([[href="(.-)"]])
          eTab[toAb]["txt"] = v:match([[title="(.-)"]])
        end

        local cosTab = eTab[math.random(#eTab)]

        today_title.setText(cosTab.txt)
        today_author.setText("闲言Sup会员点击此处查看答案\n再次点击即可刷新答案\n益智猜疑，脑筋急转弯")
        today_text.setText""
        
        daan.onClick=function()
          if isVip() == true then
            swipe1.setRefreshing(true)

            Http.get(urls..cosTab.url, nil, "gb2312",
            function(code, body)
              swipe1.setRefreshing(false)
              if code == 200 then
                local answer = body:match("答：(.-)<")

                today_author.setText("")
                today_text.setText("谜底:"..answer)

               else
                toast("网络错误:"..code)
              end
            end)
          end
        end

       else
        toast("网络错误:"..code)
      end

    end)

   else
    toast("初始化失败:可尝试重新加载")
  end
end



swipe1.setRefreshing(true)

-- 初始化
local today = os.date("%Y%m%d")
local reday = activity.getSharedData("isNewday")
if reday == today then
  thepage = luajava.astable(String(activity.getSharedData("listTab")).split(","))
  reLoadText()
  swipe1.setRefreshing(false)

 else
  local tmpPage = {}
  function tw(od)
    Http.get(urls.."/njmy/"..od,nil,"gb2312",function(code,body)

      if code == 200
        for k in body:gmatch("sy2.-'(.-)'")
          if not table.find(tmpPage, k) then
            table.insert(tmpPage, k)
          end
        end
        local ls = string.match(body, ".*sy2.-'(.-)'")
        if body:find("下一页") then
          tw(ls)
         else
          swipe1.setRefreshing(false)
          -- print("初始化完成")
          activity.setSharedData("isNewday",today)
          activity.setSharedData("listTab",table.concat(tmpPage, ","))
          thepage = table.clone(tmpPage)
          reLoadText()

        end
       else
       
        swipe1.setRefreshing(false)
        toast("初始化失败 网络错误:"..code)
      end
    end)
  end
  tw("")
end

swipe1.setOnRefreshListener{onRefresh=function()
    swipe1.setRefreshing(true)
    reLoadText()
  end}

now_content=1

today_title.onLongClick=function()
  对话框操作()
end

czts.onClick=function()
  czts.setVisibility(8)
  activity.setSharedData("naojin","true")
end

if activity.getSharedData("naojin")=="true" then
  czts.setVisibility(8)
end